// import axios from 'axios'
import { Message } from 'element-ui'
// import store from '@/store'
// import { getToken } from '@/utils/auth'

// // create an axios instance
// const service = axios.create({
//   baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
//   // withCredentials: true, // send cookies when cross-domain requests
//   timeout: 5000 // request timeout
// })

// export default service(响应拦截器)
// 导出一个axios的实例  而且这个实例要有请求拦截器 响应拦截器
import axios from 'axios'
import store from '@/store'
import router from '@/router'
const service = axios.create({
  // 解决跨越不设置基地址（用本地服务器代理转发）
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// // request interceptor 请求拦截器
service.interceptors.request.use(
  config => {
    // vuex中有token就添加
    if (store.state.user.token) {
      config.headers['Authorization'] = `Bearer ${store.state.user.token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// // response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    if (!response.data.success) {
      // 用户名或密码错误 返回错误
      return Promise.reject(new Error(response.data.message))
    } else {
      // 成功返回response
      return response
    }
  },
  async error => {
    // 如果404 token失效
    if (error.response.status === 401) {
      // 清空userInfo token
      await store.dispatch('user/logout')
      // 跳转页面
      router.push('/login?return_url=' + encodeURIComponent(router.currentRoute.fullPath))
    }
    Message({
      message: error.response.data.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export default service // 导出axios实例
